package com.cn.shuangzi.ad.custom;

import android.app.Activity;
import android.content.Context;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.reward.MediationCustomRewardVideoLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationRewardItem;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.KsErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.ThreadUtils;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsRewardVideoAd;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.model.AdExposureFailedReason;
import com.kwad.sdk.api.model.AdExposureFailureCode;
import com.kwad.sdk.api.model.AdnType;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import androidx.annotation.Nullable;

public class KsCustomerReward extends MediationCustomRewardVideoLoader {


    private KsRewardVideoAd mKsRewardVideoAd;
    private int price;

    @Override
    public void load(Context context, final AdSlot adSlot, final MediationCustomServiceConfig mediationCustomServiceConfig) {
        /**
         * 在子线程中进行广告加载
         */
        ThreadUtils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                if(KsAdSDK.getLoadManager() != null){
                    long posId = 0;
                    try {
                        posId = Long.parseLong(mediationCustomServiceConfig.getADNNetworkSlotId()); //广告位id
                    } catch (Exception e) {
                        callLoadFail(-1, "msg");
                        return;
                    }
                    KsScene scene = new KsScene.Builder(posId).build();
                    KsAdSDK.getLoadManager().loadRewardVideoAd(scene, new KsLoadManager.RewardVideoAdListener() {
                        @Override
                        public void onError(int i, String s) {
                            ADUtil.logError("快手 激励视频 onError code="+i+"，msg："+s);
                            ADManager.getInstance().setRewardKsErrorInfo(new KsErrorInfo(AdExposureFailureCode.OTHER));
                            callLoadFail(i,s);
                        }

                        @Override
                        public void onRewardVideoResult(@Nullable List<KsRewardVideoAd> list) {
                            if(list!=null){
                                ADUtil.logError("快手 激励视频 onRewardVideoResult："+list.size());
                            }else{
                                ADUtil.logError("===快手 激励视频 onRewardVideoResult===");
                            }
                        }

                        @Override
                        public void onRewardVideoAdLoad(@Nullable List<KsRewardVideoAd> list) {
                            if(list != null && list.size() > 0){
                                mKsRewardVideoAd = list.get(0);
                                ADManager.getInstance().setRewardKsAd(mKsRewardVideoAd);
                                if (isClientBidding()) {
                                    double ecpm = mKsRewardVideoAd.getECPM();
                                    if (ecpm < 0) {
                                        ecpm = 0;
                                    }
                                    price = (int) ecpm;
                                    ADUtil.logError("快手激励视频 ecpm:" + ecpm);
                                    ADManager.getInstance().setRewardKsErrorInfo(new KsErrorInfo(new AdExposureFailedReason().setAdnType(AdnType.THIRD_PARTY_AD)));
                                    callLoadSuccess(ecpm);
                                } else {
                                    callLoadSuccess();
                                }
                                mKsRewardVideoAd.setRewardAdInteractionListener(new KsRewardVideoAd.RewardAdInteractionListener() {
                                    @Override
                                    public void onAdClicked() {
                                        callRewardVideoAdClick();
                                    }

                                    @Override
                                    public void onPageDismiss() {
                                        callRewardVideoAdClosed();
                                    }

                                    @Override
                                    public void onVideoPlayError(int code, int extra) {
                                        callRewardVideoError();
                                    }

                                    @Override
                                    public void onVideoPlayEnd() {
                                        callRewardVideoComplete();
                                    }

                                    @Override
                                    public void onVideoSkipToEnd(long l) {
                                        callRewardVideoSkippedVideo();
                                    }

                                    @Override
                                    public void onVideoPlayStart() {
                                        callRewardVideoAdShow();
                                    }

                                    @Override
                                    public void onRewardStepVerify(int taskType, int currentTaskStatus) {

                                    }

                                    @Override
                                    public void onExtraRewardVerify(int extraRewardType) {

                                    }

                                    @Override
                                    public void onRewardVerify() {
                                        float amount = 0f;
                                        String name = "";
                                        if (adSlot != null && adSlot.getMediationAdSlot() != null) {
                                            amount = adSlot.getMediationAdSlot().getRewardAmount();
                                            name = adSlot.getMediationAdSlot().getRewardName();
                                        }
                                        final float finalAmount = amount;
                                        final String finalName = name;
                                        ADUtil.logError("快手 激励视频 onReward name="+name+"，amount"+amount);
                                        callRewardVideoRewardVerify(new MediationRewardItem() {
                                            @Override
                                            public boolean rewardVerify() {
                                                return true;
                                            }

                                            @Override
                                            public float getAmount() {
                                                return finalAmount;
                                            }

                                            @Override
                                            public String getRewardName() {
                                                return finalName;
                                            }

                                            @Override
                                            public Map<String, Object> getCustomData() {
                                                return null;
                                            }
                                        });
                                    }
                                });
                            } else {
                                callLoadFail(ADConst.LOAD_ERROR,"no data");
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        /**
         * 在子线程中进行广告是否可用的判断
         */
        Future<MediationConstant.AdIsReadyStatus> future = ThreadUtils.runOnThreadPool(new Callable<MediationConstant.AdIsReadyStatus>() {
            @Override
            public MediationConstant.AdIsReadyStatus call() throws Exception {
                if (mKsRewardVideoAd != null && mKsRewardVideoAd.isAdEnable()) {
                    return MediationConstant.AdIsReadyStatus.AD_IS_READY;
                } else {
                    return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
                }
            }
        });
        try {
            MediationConstant.AdIsReadyStatus result = future.get(500, TimeUnit.MILLISECONDS);//设置500毫秒的总超时，避免线程阻塞
            if (result != null) {
                return result;
            } else {
                return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
    }

    @Override
    public void onPause() {
        ADUtil.logError("快手 激励视频 onPause");
    }

    @Override
    public void onResume() {
        ADUtil.logError("快手 激励视频 onResume");
    }

    @Override
    public void onDestroy() {
        ADUtil.logError("快手 激励视频 onDestroy");
    }

    @Override
    public void receiveBidResult(boolean win, double winnerPrice, int loseReason, Map<String, Object> extra) {
        super.receiveBidResult(win, winnerPrice, loseReason, extra);
        ADUtil.logError("快手 激励视频 receiveBidResult");
    }

    @Override
    public void showAd(Activity activity) {
        ADUtil.logError("快手 激励视频 showAd");
        if (mKsRewardVideoAd!=null&&price > 0) {
            mKsRewardVideoAd.setBidEcpm(price,price-ADConst.YUAN*2);
            ADUtil.logError("=======上报快手 激励视频 竞价成功数据======="+price);
        }
        mKsRewardVideoAd.showRewardVideoAd(activity,null);
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }
}
